package org.sws.domain.activity.service.quota.rule.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.sws.domain.activity.model.entity.ActivityCountEntity;
import org.sws.domain.activity.model.entity.ActivityEntity;
import org.sws.domain.activity.model.entity.ActivitySkuEntity;
import org.sws.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import org.sws.domain.activity.repository.IActivityRepository;
import org.sws.domain.activity.service.armory.IActivityDispatch;
import org.sws.domain.activity.service.quota.rule.AbstractActivityChain;
import org.sws.types.enums.ResponseCode;
import org.sws.types.exception.AppException;

import javax.annotation.Resource;

/**
 * @Author sws
 * @Date 2025/3/19 09:38
 * @description: sku库存校验
 */
@Slf4j
@Component("activity_sku_stock_action")
public class ActivitySkuStockAction extends AbstractActivityChain {
    @Resource
    private IActivityDispatch activityDispatch;
    @Resource
    private IActivityRepository activityRepository;
    @Override
    public boolean action(ActivitySkuEntity activitySkuEntity, ActivityEntity activityEntity, ActivityCountEntity activityCountEntity) {
        log.info("活动责任链-sku库存处理【校验&扣减】开始。sku:{} activityId:{}", activitySkuEntity.getSku(), activityEntity.getActivityId());
        // 扣减 sku库存
        boolean success = activityDispatch.subtractSkuStock(activitySkuEntity.getSku(), activityEntity.getEndDateTime());
        // true；库存扣减成功
        if (success) {
            log.info("活动责任链-商品库存处理【扣减成功】sku:{} activityId:{}", activitySkuEntity.getSku(), activityEntity.getActivityId());
            // 写入延迟队列，延迟消费更新库存记录
            activityRepository.activitySkuStockConsumeSendQueue(ActivitySkuStockKeyVO.builder()
                    .sku(activitySkuEntity.getSku())
                    .activityId(activityEntity.getActivityId())
                    .build());
            return true;
        }
        throw new AppException(ResponseCode.ACTIVITY_COUNT_OVER.getCode(), ResponseCode.ACTIVITY_COUNT_OVER.getInfo());
    }
}
